<template>
  <div class="app-container">
    <div class="header">
      <el-page-header @back="goBack" :content="resourceInfo.title || '课程详情'" />
    </div>

    <el-card class="box-card" v-loading="loading">
      <div class="resource-info">
        <h2>{{ resourceInfo.title }}</h2>
        <div class="info-item">
          <span class="label">资源类型：</span>
          <el-tag size="small">{{ getResourceType(resourceInfo.type) }}</el-tag>
        </div>
        <div class="info-item">
          <span class="label">专业领域：</span>
          <el-tag size="small" type="success">{{ getDomainName(resourceInfo.domain) }}</el-tag>
        </div>
        <div class="info-item">
          <span class="label">难度等级：</span>
          <el-rate v-model="resourceInfo.level" disabled show-score text-color="#ff9900" />
        </div>
        <div class="info-item">
          <span class="label">资源描述：</span>
          <p class="description">{{ resourceInfo.description }}</p>
        </div>
      </div>

      <!-- 视频播放器 -->
      <div v-if="resourceInfo.type === 2" class="player-container">
        <video
          ref="videoPlayer"
          class="video-player"
          :src="resourceInfo.path"
          controls
          @play="onPlay"
          @pause="onPause"
          @ended="onEnded"
          @timeupdate="onTimeUpdate"
        ></video>
      </div>

      <!-- 音频播放器 -->
      <div v-if="resourceInfo.type === 3" class="player-container">
        <audio
          ref="audioPlayer"
          class="audio-player"
          :src="resourceInfo.path"
          controls
          @play="onPlay"
          @pause="onPause"
          @ended="onEnded"
          @timeupdate="onTimeUpdate"
        ></audio>
      </div>

      <!-- 文档预览 -->
      <div v-if="resourceInfo.type === 1" class="document-container">
        <iframe :src="resourceInfo.path" frameborder="0" width="100%" height="600px"></iframe>
      </div>

      <!-- 图片预览 -->
      <div v-if="resourceInfo.type === 4" class="image-container">
        <el-image :src="resourceInfo.path" :preview-src-list="[resourceInfo.path]"></el-image>
      </div>

      <!-- 链接跳转 -->
      <div v-if="resourceInfo.type === 5" class="link-container">
        <el-button type="primary" @click="openLink">打开链接</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { http } from '@/api'

export default {
  name: 'LearningDetail',
  data() {
    return {
      loading: false,
      resourceInfo: {
        id: null,
        title: '',
        type: null,
        path: '',
        description: '',
        domain: null,
        level: 1
      },
      // 播放相关数据
      isPlaying: false,
      currentTime: 0,
      lastUpdateTime: 0,
      updateInterval: 5000, // 每5秒更新一次学习记录
      learningRecord: {
        userId: this.$store.state.user.userInfo.id, // 这里应该从用户状态或登录信息中获取
        resourceId: null,
        currentLearnTime: 0,
        remark: '在线学习'
      }
    }
  },
  created() {
    const resourceId = this.$route.params.id
    if (resourceId) {
      this.getResourceDetail(resourceId)
      this.initLearningRecord(resourceId)
    }
  },
  methods: {
    getResourceType(type) {
      const types = {
        1: '文档',
        2: '视频',
        3: '音频',
        4: '图片',
        5: '链接'
      }
      return types[type] || '-'
    },
    getDomainName(domain) {
      const domains = {
        1: '铁道工程',
        2: '信号控制',
        3: '机车车辆'
      }
      return domains[domain] || '-'
    },
    async getResourceDetail(id) {
      this.loading = true
      try {
        const res = await http.resource.getDetail(id)
        this.resourceInfo = res.data
        this.learningRecord.resourceId = id
      } catch (error) {
        console.error(error)
        this.$message.error('获取资源详情失败')
      }
      this.loading = false
    },
    async initLearningRecord(resourceId) {
      this.learningRecord.resourceId = resourceId
      // 初始化学习记录
      await this.updateLearningRecord(0)
    },
    onPlay() {
      this.isPlaying = true
      this.lastUpdateTime = Date.now()
    },
    onPause() {
      this.isPlaying = false
      const player = this.$refs.videoPlayer || this.$refs.audioPlayer
      if (player) {
        this.updateLearningRecord(Math.floor(player.currentTime))
      }
    },
    onEnded() {
      this.isPlaying = false
      const player = this.$refs.videoPlayer || this.$refs.audioPlayer
      if (player) {
        this.updateLearningRecord(Math.floor(player.duration))
      }
    },
    onTimeUpdate(e) {
      const now = Date.now()
      this.currentTime = e.target.currentTime

      // 每隔一定时间更新学习记录
      if (this.isPlaying && (now - this.lastUpdateTime) >= this.updateInterval) {
        this.updateLearningRecord(Math.floor(this.currentTime))
        this.lastUpdateTime = now
      }
    },
    async updateLearningRecord(currentTime) {
      try {
        const data = {
          ...this.learningRecord,
          currentLearnTime: currentTime
        }
        await http.learning.save(data)
      } catch (error) {
        console.error(error)
        this.$message.error('更新学习记录失败')
      }
    },
    openLink() {
      window.open(this.resourceInfo.path, '_blank')
    },
    goBack() {
      // 退出前保存当前学习时长
      if (this.isPlaying) {
        const player = this.$refs.videoPlayer || this.$refs.audioPlayer
        if (player) {
          this.updateLearningRecord(Math.floor(player.currentTime))
        }
      }
      this.$router.push({ name: 'LearningRecord' })
    }
  },
  beforeDestroy() {
    // 组件销毁前保存学习记录
    if (this.isPlaying) {
      const player = this.$refs.videoPlayer || this.$refs.audioPlayer
      if (player) {
        this.updateLearningRecord(Math.floor(player.currentTime))
      }
    }
  }
}
</script>

<style scoped lang="scss">

.header {
  margin-bottom: 20px;
}

.resource-info {
  margin-bottom: 20px;

  h2 {
    margin-bottom: 20px;
    color: #303133;
  }

  .info-item {
    margin-bottom: 15px;

    .label {
      color: #606266;
      margin-right: 10px;
    }

    .description {
      margin-top: 5px;
      color: #606266;
      line-height: 1.6;
    }
  }
}

.player-container {
  width: 100%;
  margin: 20px 0;
  display: flex;
  justify-content: center;

  .video-player {
    width: 100%;
    max-width: 800px;
    height: auto;
  }

  .audio-player {
    width: 100%;
    max-width: 500px;
  }
}

.image-container {
  text-align: center;
  margin: 20px 0;

  .el-image {
    max-width: 100%;
    max-height: 600px;
  }
}

.link-container {
  text-align: center;
  margin: 20px 0;
}
</style>
